﻿'
' PDSplitter - http://www.dotnetcode.it
' Copyright (c) 2011
' by DotNetCode.IT
'
' Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
' documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
' the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
' to permit persons to whom the Software is furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all copies or substantial portions 
' of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
' DEALINGS IN THE SOFTWARE.
'

Imports System.Windows.Forms
Imports PdfSharp.Pdf
Imports PdfSharp.Pdf.IO
Imports System.IO
Imports Microsoft.Win32
Imports System.Reflection

Public Class frmMain

    Friend WithEvents button As Button
    Private messageboxTitle As String = "Pdf Splitter"
    <System.Runtime.InteropServices.DllImport("ole32.dll")> _
    Private Shared Sub CoFreeUnusedLibraries()

    End Sub

    Public Property OutputFolder As String
    Public Property InputFileName As String
    Public Property InputFilePageCount As Integer
    Public Shared ReadOnly Property OptIn As Boolean
        Get
            Return Convert.ToBoolean(Utility.GetConfigurationSetting("OptIn", "true"))

        End Get
    End Property

    Public Property SplitPageFrom As Integer
        Get
            Return CInt(txtPageFrom.Text)
        End Get
        Set(ByVal value As Integer)
            txtPageFrom.Text = value.ToString
        End Set
    End Property
    Public Property SplitPageTo As Integer
        Get
            Return CInt(txtPageTo.Text)
        End Get
        Set(ByVal value As Integer)
            txtPageTo.Text = value.ToString
        End Set
    End Property

    Public Property SplitPageSize As Integer
        Get
            Return CInt(txtPageSize.Text)
        End Get
        Set(ByVal value As Integer)
            txtPageSize.Text = value.ToString
        End Set
    End Property


    ''' <summary>
    ''' Selects the PDF file.
    ''' </summary>
    ''' <author>LCO (29/07/2011)</author>
    ''' <includesource>yes</includesource>
    Public Sub SelectPdfFile()
        If OpenFileDialog1.ShowDialog = DialogResult.OK Then
            InputFileName = OpenFileDialog1.FileName
            Dim selectedPdfDocument As PdfDocument = PdfReader.Open(InputFileName, PdfDocumentOpenMode.InformationOnly)
            InputFilePageCount = selectedPdfDocument.PageCount
            txtPageTo.Text = InputFilePageCount.ToString
            AxAcroPDF1.LoadFile(InputFileName)

        End If
        lblStatusMessage.Text = ""
    End Sub

    ''' <summary>
    ''' Selects the output folder.
    ''' </summary>
    ''' <author>LCO (29/07/2011)</author>
    ''' <includesource>yes</includesource>
    Private Sub SelectOutputFolder()
        FolderBrowserDialog1.SelectedPath = Me.OutputFolder
        If FolderBrowserDialog1.ShowDialog = DialogResult.OK Then
            Me.OutputFolder = FolderBrowserDialog1.SelectedPath
            Configuration.ConfigurationManager.AppSettings("OutputFolder") = Me.OutputFolder
            Utility.SaveRegistrySetting("OutputFolder", Me.OutputFolder)
        End If
        lblStatusMessage.Text = ""
    End Sub

    Private Sub btnOpenFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpenFile.Click
        SelectPdfFile()
    End Sub

    Private Sub frmMain_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        If AxAcroPDF1 IsNot Nothing Then
            AxAcroPDF1.Dispose()
            System.Windows.Forms.Application.DoEvents()
            CoFreeUnusedLibraries()
        End If
    End Sub


    <PreEmptive.Attributes.Setup(CustomEndPoint:="so-s.info/PreEmptive.Web.Services.Messaging/MessagingServiceV2.asmx")> _
    <PreEmptive.Attributes.Teardown()> _
    Private Sub frmMain_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        button = New Button
        AddHandler button.Click, AddressOf btnExecuteSplit_Click
        Me.AcceptButton = button
        If Utility.ReadRegistrySetting("OutputFolder").Trim <> "" Then
            Me.OutputFolder = Utility.ReadRegistrySetting("OutputFolder").Trim
        ElseIf Configuration.ConfigurationManager.AppSettings("OutputFolder").Trim <> "" Then
            Me.OutputFolder = Configuration.ConfigurationManager.AppSettings("OutputFolder").Trim
        Else
            Me.OutputFolder = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\output"
        End If

        If Not System.IO.Directory.Exists(Me.OutputFolder) Then
            System.IO.Directory.CreateDirectory(Me.OutputFolder)
        End If
        Me.InputFileName = ""
    End Sub

    Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenToolStripMenuItem.Click
        SelectPdfFile()
    End Sub

    Private Sub btnExecuteSplit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExecuteSplit.Click
        If Me.InputFileName.Trim = "" Then
            MessageBox.Show(My.Resources.SelectPdfFile, messageboxTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            SelectPdfFile()
        Else
            'Check split configuration
            If CheckSplitParameters() Then
                ExecuteSplit()
            End If
            'Run

        End If

    End Sub

    Private Function CheckSplitParameters() As Boolean
        Dim result As Boolean = True
        Dim Message As String = ""
        If SplitPageFrom > SplitPageTo Then
            Message = My.Resources.PageToGreaterPageFrom
            txtPageTo.Focus()
        ElseIf SplitPageSize > InputFilePageCount Then
            Message = My.Resources.PageSizeLowerPageCount
            txtPageSize.Focus()
        End If
        If Message.Length > 0 Then
            result = False
            MessageBox.Show(Message, messageboxTitle, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End If

        Return result

    End Function

    <PreEmptive.Attributes.Feature("Split")> _
    Private Sub ExecuteSplit()
        Dim name As String = Path.GetFileNameWithoutExtension(InputFileName)
        lblStatusMessage.Text = My.Resources.SplittingStarted
        Application.DoEvents()
        Dim selectedPdfDocument As PdfDocument = PdfReader.Open(InputFileName, PdfDocumentOpenMode.Import)
        Dim CounterMax As Integer = CInt((SplitPageTo - (SplitPageFrom - 1)) / SplitPageSize)
        If ((SplitPageTo - (SplitPageFrom - 1)) Mod SplitPageSize) > 0 Then
            CounterMax += 1
        End If
        Dim counter As Integer = 0
        For pageIndex As Integer = SplitPageFrom - 1 To SplitPageTo - 1 Step SplitPageSize
            counter += 1

            ' Create new document
            Dim outputPDFDocument As New PdfDocument()
            outputPDFDocument.Version = selectedPdfDocument.Version
            Dim pageTo As Integer = pageIndex + 1 + SplitPageSize
            If pageTo > selectedPdfDocument.PageCount Then
                pageTo = selectedPdfDocument.PageCount
            End If
            outputPDFDocument.Info.Title = [String].Format(My.Resources.PdfDocumentTitle, pageIndex + 1, pageTo)
            outputPDFDocument.Info.Creator = selectedPdfDocument.Info.Creator
            lblStatusMessage.Text = String.Format(My.Resources.CreatingFile, counter, CounterMax, outputPDFDocument.Info.Title)
            Application.DoEvents()

            For k As Integer = 0 To SplitPageSize - 1
                ' Add the page
                If (pageIndex + k) < InputFilePageCount Then
                    Dim pag As PdfPage = selectedPdfDocument.Pages(pageIndex + k)
                    If cmbRotate.Text.Trim <> "" Then
                        If IsNumeric(cmbRotate.Text) Then
                            pag.Rotate = CInt(cmbRotate.Text)
                        End If
                    End If
                    outputPDFDocument.AddPage(pag)
                End If

            Next
            'Save
            outputPDFDocument.Save(String.Format(My.Resources.PdfFilename, OutputFolder, name, pageIndex + 1))
            lblStatusMessage.Text = String.Format(My.Resources.CreatedFile, counter, CounterMax, outputPDFDocument.Info.Title)
            Application.DoEvents()
        Next
        lblStatusMessage.Text = My.Resources.Done
        MessageBox.Show(My.Resources.Done, messageboxTitle, MessageBoxButtons.OK, MessageBoxIcon.Information)
        If OpenAfterExecutionToolStripMenuItem.Checked Then
            Process.Start("explorer.exe", Me.OutputFolder)
        End If

    End Sub
    Private Sub btnSelectOutputFolder_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSelectOutputFolder.Click
        SelectOutputFolder()
    End Sub

    Private Sub ChangeFolderToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ChangeFolderToolStripMenuItem.Click
        SelectOutputFolder()
    End Sub

    Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
        Me.Close()
    End Sub

    Private Sub OpenAfterExecutionToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenAfterExecutionToolStripMenuItem.Click
        OpenAfterExecutionToolStripMenuItem.Checked = Not OpenAfterExecutionToolStripMenuItem.Checked
    End Sub

    Private Sub txtPageTo_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtPageTo.TextChanged
        If Not IsNumeric(txtPageTo.Text) Then
            txtPageTo.Text = InputFilePageCount
        ElseIf SplitPageTo > InputFilePageCount Then
            SplitPageTo = InputFilePageCount
        End If
    End Sub

    Private Sub txtPageFrom_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtPageFrom.TextChanged
        If Not IsNumeric(txtPageFrom.Text) Then
            txtPageFrom.Text = 1
        ElseIf SplitPageFrom < 1 Then
            SplitPageFrom = 1
        End If
    End Sub

    Private Sub txtSize_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtPageSize.TextChanged
        If Not IsNumeric(txtPageSize.Text) Then
            txtPageSize.Text = 1
        ElseIf SplitPageSize < 1 Then
            SplitPageSize = 1
        End If
    End Sub


    Private Sub frmMain_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown

        If e.Control And e.KeyCode = Keys.A Then
            MessageBox.Show("Author: Luca Congiu", messageboxTitle, MessageBoxButtons.OK, MessageBoxIcon.Information)
        ElseIf e.Control And e.KeyCode = Keys.F Then
            SelectPdfFile()
        ElseIf e.Control And e.KeyCode = Keys.O Then
            SelectOutputFolder()
        ElseIf e.Control And e.KeyCode = Keys.S Then
            ExecuteSplit()
        End If

    End Sub

End Class
